package com.orange.studio.dbk.fragments;


import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.meta.gui.quickaction.ActionItem;
import com.meta.gui.quickaction.QuickAction;
import com.orange.studio.dbk.R;
import com.orange.studio.dbk.activities.HomeActivity;
import com.orange.studio.dbk.adapters.ListSongAdapter;
import com.orange.studio.dbk.customviews.LoadMoreListView;
import com.orange.studio.dbk.dao.FavioritesDAO;
import com.orange.studio.dbk.dao.SongDAO;
import com.orange.studio.dbk.dto.SearchDTO;
import com.orange.studio.dbk.dto.SongDTO;
import com.orange.studio.dbk.utils.AppConfig.SEARCH_TYPE;
import com.orange.studio.dbk.utils.DBKUtils;
import com.orange.studio.uicore.customviews.LoadMoreListViewUICore;

public class HomeFragment extends BaseFragment {
	private ListSongAdapter mAdapter;
	private SongDAO mSongDAO;
	
	private GetSongFromStore mGetSongFromStore=null;
	private View mVolNumber=null;
	private TextView mTypeNumber=null;
	private QuickAction menu=null;
	private ImageView mSubmitSearch=null;
	private TextView mSearchText=null;
	private SearchDTO search=null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.fragment_layout_home,
					container, false);	
			mActivity=(HomeActivity) getActivity();
			initView();
			initListener();
			createPopupMenu();
		} else {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		return mView;
	}
	private void initView(){
		initNotFoundAndLoadingView();
		mVolNumber=(LinearLayout)mView.findViewById(R.id.menuTypeNumber);
		mTypeNumber=(TextView)mView.findViewById(R.id.currentTypeNumber);
		mTypeNumber.setText(getActivity().getString(R.string.type_5_number));
		mSubmitSearch=(ImageView)mView.findViewById(R.id.submitSearch);
		mSearchText=(TextView)mView.findViewById(R.id.searchText);
		
		mSongDAO=new SongDAO(getActivity());
		
		mListView=(LoadMoreListViewUICore)mView.findViewById(R.id.mListView);		
		mAdapter=new ListSongAdapter(getActivity(),this);
		mListView.setAdapter(mAdapter);		
		mActivity.setListSongAdapter(mAdapter);
		search=new SearchDTO();
		search.language=1;
		
	}
	private void initListener(){
		initRetryButtonListener();
		mVolNumber.setOnClickListener(this);
		mSubmitSearch.setOnClickListener(this);
		mListView.setOnLoadMoreListener(this);
	}
	private void createPopupMenu(){
		menu=new QuickAction(getActivity());
		menu.setOnActionItemClickListener(this);
		ActionItem item1=new ActionItem(111, getActivity().getString(R.string.type_5_number));
		ActionItem item2=new ActionItem(112, getActivity().getString(R.string.type_6_number));
		
		
		menu.addActionItem(item1);
		menu.addActionItem(item2);		
		
	}
	private void showPopupMenu(View v) {		
		menu.show(v);
	}
	@Override
	public void onClick(View v) {
		int id=v.getId();
		switch (id) {
		case R.id.menuTypeNumber:
			showPopupMenu(mVolNumber);
			break;
		case R.id.submitSearch:
			mAdapter.cleanListData();
			pageNo=1;
			search.type=SEARCH_TYPE.SEARCH_TYPE_SONG_NAME;
			getData();
			break;
		default:
			super.onClick(v);
			break;
		}		
	}
	@Override
	public void onItemClick(QuickAction source, int pos, int actionId) {
		switch (actionId) {
		case 111:
			mTypeNumber.setText(getActivity().getString(R.string.type_5_number));
			search.manufacture=1;
			pageNo=1;
			getData();
			break;
		case 112:
			mTypeNumber.setText(getActivity().getString(R.string.type_6_number));
			search.manufacture=2;
			pageNo=1;
			getData();
			break;
		default:
			super.onItemClick(source, pos, actionId);
			break;
		}
	}
	@Override
	public void onLoadMore() {
		super.onLoadMore();
			getData();
	}
	private void getData(){
		if(mGetSongFromStore==null || mGetSongFromStore.getStatus()==Status.FINISHED){
			mGetSongFromStore=new GetSongFromStore();
			mGetSongFromStore.execute();
		}
	}
	private class UpdateSongLiked extends AsyncTask<SongDTO, Void, Void>{
		
		@Override
		protected Void doInBackground(SongDTO... params) {
			SongDTO song=params[0];
			boolean isLiked=(song.getLiked()>0?true:false);
			try {
				mSongDAO.open();
				mSongDAO.updateSongLiked(song.getId(), isLiked);
			} catch (Exception e) {
			}
			finally{
				mSongDAO.close();
			}
			return null;
		}
		
	}
	private class GetSongFromStore extends AsyncTask<Void, Void, List<SongDTO>>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showNotFoundOrLoadingView(false, true);
			if(pageNo==1){
				mListView.setVisibility(View.GONE);
			}
		}
		@Override
		protected List<SongDTO> doInBackground(Void... arg0) {
			List<SongDTO> result=null;
			try {
				getListFaviorites();
				mSongDAO.open();
				//result=mSongDAO.getAll(typeNumber,pageNo);
				search.key=mSearchText.getText().toString().trim();
				result=mSongDAO.searchSongs(search, pageNo);
			} catch (Exception e) {
				Log.i("SONGDAO OPEN", e.getMessage().toString());
			}
			finally{
				mSongDAO.close();
			}
			return result;
		}		
		@Override
		protected void onPostExecute(List<SongDTO> result) {
			super.onPostExecute(result);
			try {
				if(result!=null && result.size()>0){
					DBKUtils.checkUserLiked(result, mActivity.getFavioriteIds());
					if(pageNo==1){
						mAdapter.updateListData(result);
					}
					else{
						mAdapter.insertListData(result);
					}
					pageNo++;
				}
				if(mAdapter.getCount()<1){
					showNotFoundOrLoadingView(true, false);
					mListView.setVisibility(View.GONE);
				}else{
					showNotFoundOrLoadingView(false, false);
					mListView.setVisibility(View.VISIBLE);
				}
			} catch (Exception e) {
			}
			finally{
				mListView.onLoadMoreComplete();
			}			
		}		
	}
	@Override
	public void onResume() {
		super.onResume();		
		//updateListView();	
		if(mAdapter!=null && mAdapter.getCount()<1){
			getData();
		}
	}
	private void updateListView(){
		if(mActivity==null){
			mActivity=(HomeActivity) getActivity();
		}
		List<Integer> listRemovedIds=mActivity.getFavioriteRemovedIds();
		if(listRemovedIds==null){
			mActivity.setFavioriteRemovedIds(new ArrayList<Integer>());
		}else{
			if(listRemovedIds!=null && listRemovedIds.size()>0){
				boolean isNotifyDataSetChanged=false;
				for (int i = 0; i < listRemovedIds.size(); i++) {
					isNotifyDataSetChanged=mAdapter.setUnLikeSongs(listRemovedIds.get(i));
				}
				if(isNotifyDataSetChanged){
					mAdapter.notifyDataSetChanged();
				}
			}
		}
		mActivity.getFavioriteRemovedIds().clear();
	}
	@Override
	public void setLiked(SongDTO song) {
		//UpdateSongLiked mUpdateSongLiked=new UpdateSongLiked();
		//mUpdateSongLiked.execute(song);
		try {
			if(song.getLiked()<1){
				DBKUtils.setUserLikedIds(mActivity.getFavioriteIds(), song.getId());
				DBKUtils.setUserLikeSongs(mAdapter.getListData(), song.getId());
			}
			else{
				DBKUtils.setUserUnLikedIds(mActivity.getFavioriteIds(), song.getId());
				DBKUtils.setUserUnLikeSongs(mAdapter.getListData(), song.getId());
			}
			if(mActivity.getFavioriteIds().size()>0){
				FavioritesDAO.getInstance().setFaviorites(mActivity.getFavioriteIds());
			}
		} catch (Exception e) {
			Log.e("SET USER LIKE", e.getMessage().toString());
		}
	}
}
